/*
 * @Author: 陈永浩(cyh1231wp@163.com)
 * @Date: 2021-02-27 10:38:32
 * @LastEditors: 陈永浩(cyh1231wp@163.com)
 * @LastEditTime: 2021-03-05 16:37:04
 */
const { app, BrowserWindow, Menu, ipcMain } = require('electron')
const path = require('path')
const url = require('url')
const helper = require('./helper')
const sudo = require('sudo-prompt');

let options = { name: 'Phala Tools' };
let exec = helper.promisify(sudo.exec, sudo);
let devPort = 8090;

function createWindow() {
  Menu.setApplicationMenu(null)
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      preload: __dirname + '/preload.js'
    }
  })

  if (process.env.NODE_ENV == 'DEV') {
    win.loadURL(`http://localhost:${devPort}/`)
  } else {
    // win.loadFile('dist/index.html')
    win.loadURL(url.format({
      pathname: path.join(__dirname, 'dist/index.html'),
      protocol: 'file:',
      slashes: true
    }))
  }

  win.webContents.openDevTools();
}

app.whenReady()
  .then(createWindow)
  .then(async () => {
    // const data = await exec('phala status', options)
    // console.log(data);
  })

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

ipcMain.on('async', async (event, arg) => {
  console.log(arg)
  const res = await exec(arg, options)
  event.reply('async-reply', res)
})

ipcMain.on('sync', async (event, arg) => {
  console.log(arg)
  event.returnValue = await exec(arg, options)
})